import { Logger, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { ArticlesModule } from './articles/articles.module';
import { CategoriesModule } from './categories/categories.module';
import { TagsModule } from './tags/tags.module';
import { CommentsModule } from './comments/comments.module';
import { FriendsModule } from './friends/friends.module';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core';
import { RedisModule } from '@nestjs-modules/ioredis';
import { RedisService } from './common/service/redis.service';
import { ConfigModule } from '@nestjs/config';
import { ScheduleModule } from '@nestjs/schedule';
import { TaskService } from './task/task.service'
import { CacheService } from "./task/cacheService.service";
import { ContentModule } from './content/content.module';
import { UploadModule } from './upload/upload.module';

const envFilePath = ['.env.development.local',`.env.${process.env.NODE_ENV}`];

@Module({
  imports: [
    // 配置环境变量
    ConfigModule.forRoot({
      isGlobal:true,
      envFilePath: envFilePath
    }),
    // 配置typeorm
    TypeOrmModule.forRoot({
      type: 'mysql', //数据库类型
      host: process.env.DATABASE_HOST, //主机
      port: +process.env.DATABASE_PORT, //端口
      username: process.env.DATABASE_USERNAME, //用户名
      password: process.env.DATABASE_PASSWORD, //密码
      database: process.env.DATABASE_DATABASE, //数据库名
      autoLoadEntities: true, //自动加载模块
      synchronize: process.env.IS_LOCAL === "1" ? true : false, // 同步：确保TypeORM实体每次运行应用程序时都会与数据库同步 !生产环境中时必须禁用! 会根据Entity生成mysql表格
      logging: process.env.IS_LOCAL === "1" ? true : false, // 打印日志 启动printSql()
    }),
    //配置节流模块
    ThrottlerModule.forRoot([{
      ttl: 1000, // 单位时间内 毫秒
      limit: 100, // 最大允许请求次数
    }]),
    // 配置redis
    RedisModule.forRootAsync({
      useFactory: () => ({
          type: 'single',
          url: process.env.REDIS_URL,
          options: {
            password: process.env.REDIS_PASSWORD,
            stringNumbers: true // 启用后redis返回的数字会被转换为字符串
          }
      }),
    }),
    // 配置定时任务
    ScheduleModule.forRoot(),
    AuthModule,
    UsersModule,
    ArticlesModule,
    TagsModule,
    CategoriesModule,
    CommentsModule,
    FriendsModule,
    ContentModule,
    UploadModule
  ],
  controllers: [AppController],
  providers: [
    AppService,
    RedisService,
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard
    },
    TaskService,
    CacheService,
    Logger
  ]
})

export class AppModule {}